var currComunityId = "";
var uMap = new Map();
var dictKeyArray = [];
layui.use(['element','table','form','layer'], function(){
    var table = layui.table,
        form = layui.form,
        $ = layui.jquery,
        layer = layui.layer;

    $('#communitySearch').bind('keypress', function (event) {
        if (event.keyCode == "13") {
            var keyWords = $.trim($(this).val());
            loadCommunityList(keyWords);
        }
    });

    loadCommunityList('');

    addDevice = function () {
        $("#resource_form")[0].reset();
        $("#upload_form").attr("disabled", false);
        $("#upload_form").attr("class", "layui-btn");
        $("#blockId").removeAttr("disabled");
        $("#deviceName").removeAttr("disabled");
        $("#deviceNo").removeAttr("disabled");
        $("#nickName").removeAttr("disabled");
        $("#typeId").removeAttr("disabled");
        layer.open({
            type: 1
            , title: '创建设备'
            , area: ['55%', '80%']
            , content: $('#uploadDiv')
        });
    };

    function loadCommunityList(name) {
        $.get('/qzsqDevice/loadCommunityList', {"name":name}, function (result) {
            if(result != null){
                if(result.data != null){
                    var data = result.data;
                    let communityList = '<div style="background-color: #f1f1f1"  onclick="changeUnit(this)" id="" class="floor-item"><div class="floor-item-text">全部</div></div>';
                    var a$opt_html = "<option value=''>请选择</option>";
                    for (let i = 0; i < data.length; i++) {
                        var id = data[i].communityId;
                        var name = data[i].communityName;
                        communityList += '<div onclick="changeUnit(this)" id="' + id + '" class="floor-item"><div class="floor-item-text">' + name + '</div></div>'
                        a$opt_html += "<option value='" + id + "'>" + name + "</option>";
                    }
                    layui.$('.floor-group').html(communityList);
                    $("#communityId").empty().append(a$opt_html);
                    form.render('select');
                    loadDeviceTable(currComunityId);
                    loadBuildingList(currComunityId,'searchBlock','searchUnit');
                    //loadBuildingList($("#communityId").val(),'blockId','unitId');
                }
            }

        });
    }

    function formatTime(data){
        return data ? data.replace("T", " "):"";
    }

    form.on('select(userName)',function (data) {
        var sInfo = uMap.get(data.value);
        if(sInfo){
            $("#phone").val(sInfo.phone);
            if(sInfo.certificateNum){
                $("#certificateType").val("0");//身份证
                $("#certificateNum").val(sInfo.certificateNum);
            }
            if(sInfo.faceData !== null && sInfo.faceData !== "" ){
                $("#userFaceInfo").val(sInfo.faceData);
                $('#demo1').attr('src', sInfo.faceData);
            }
            form.render();
        }
    });

    form.on('select(typeSelect)',function (data) {
        if(data.value == '1'){
            $("#blockId").attr("disabled","disabled");
            $("#unitId").attr("disabled","disabled");
        }else {
            $("#blockId").removeAttr("disabled");
            $("#unitId").removeAttr("disabled");
        }
        form.render();
    });

    form.on('select(communityId)',function (data) {
        loadBuildingList(data.value,'blockId','unitId');
    });

    form.on('select(blockId)',function (data) {
        loadUnitList(data.value,'unitId');
    });

    form.on('select(searchBlock)',function (data) {
        loadUnitList(data.value,'searchUnit');
    });

    function loadDeviceTable(comId) {
        table.render({
            elem: '#deviceTable'
            ,url:'/qzsqDevice/list'
            ,title: '设备管理'
            ,where: {'communityId': comId}
            ,cols: [[
                {field: 'xh',type:'numbers', title: '序号',}
                ,{field:'deviceName', title:'设备名称',align:'center'}
                ,{field:'deviceNo', title:'设备编号',align:'center'}
                ,{field:'serialNum', title:'设备序列号',align:'center'}
                ,{field:'type', title:'设备类型',align:'center'}
                ,{field:'sbly', title:'设备功能',align:'center',templet:function (data) {
                        return parseSbly(data.sbly);
                    }}
                ,{field:'nickName', title:'品牌型号',align:'center'}
                ,{field:'location', title:'设备位置',align:'center'}
                ,{field:'communityName', title:'所属小区',align:'center'}
                ,{field:'blockName', title:'所属楼栋',align:'center'}
                ,{field:'unitName', title:'所属单元',align:'center'}
                ,{field:'right',title:'操作',toolbar:'#barOperate',align:'center',width:220}
            ]]
            ,page: true
        });
    }

    table.on('tool(deviceTable)',function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'edit':
                loadBuildingList(data.communityId,'blockId','unitId',data.blockId,data.unitId);
                $("#update_form").attr("disabled", false);
                $("#update_form").attr("class", "layui-btn");
                $("#id").val(data.id);
                $("#deviceName").val(data.deviceName);
                $("#deviceNo").val(data.deviceNo);
                $("#nickName").val(data.nickName);
                $("#typeId").val(data.typeId);
                $("#communityId").val(data.communityId);
                $("#blockId").val(data.blockId);
                $("#unitId").val(data.unitId);
                $("#location").val(data.location);
                $("#blockId").attr("disabled","disabled");
                if(data.deviceName){
                    $("#deviceName").attr("disabled","disabled");
                }
                if(data.deviceNo){
                    $("#deviceNo").attr("disabled","disabled");
                }
                if(data.nickName){
                    $("#nickName").attr("disabled","disabled");
                }
                if(data.typeId){
                    $("#typeId").attr("disabled","disabled");
                }else {
                    $("#typeId").removeAttr("disabled");
                }
                if(data.typeId == '1'){
                    $("#blockId").attr("disabled","disabled");
                    $("#unitId").attr("disabled","disabled");
                }else {
                    $("#blockId").removeAttr("disabled");
                    $("#unitId").removeAttr("disabled");
                }
                form.render();
                layer.open({
                    type: 1
                    , title: '编辑门禁设备'
                    , area: ['55%', '70%']
                    , content: $('#uploadDiv')
                });
                break;
            case 'delete':
                layer.confirm('确定要删除吗?', {
                }, function(){
                    layer.load();
                    $.get('/qzsqDevice/delete',{id:data.id},function (res) {
                        layer.msg(res.msg,{
                            time:500,
                            end:function () {
                                table.reload('deviceTable');
                                layer.closeAll();
                            }
                        });
                    });
                });
                break;

        }
    });

    form.on('submit(queryDevice)',function () {
        var name = $("#searcheKey").val();
        var blockId = $("#searchBlock").val();
        var unitId = $("#searchUnit").val();
        // if(!currComunityId){
        //     table.reload('deviceTable',[]);
        //     return false;
        // }
        table.reload('deviceTable',{
            where: {communityId:currComunityId,name:name,blockId:blockId,unitId:unitId}
            ,page:  {
                curr:1
            }
        });
        return false;
    });

    form.on('submit(upload_form)',function(data){
        $("#upload_form").attr("disabled", true);
        $("#upload_form").attr("class", "layui-btn layui-btn-disabled");
        data.field.type = $("#typeId").find("option:selected").text();
        data.field.communityName = $("#communityId").find("option:selected").text();
        if(data.field.blockId){
            data.field.blockName = $("#blockId").find("option:selected").text();
        }
        if(data.field.unitId){
            data.field.unitName = $("#unitId").find("option:selected").text();
        }
        layer.load();
        $.ajax({
            type: 'post',
            url: '/qzsqDevice/saveOrUpdate',
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(data.field),
            success: function (res) {
                layer.msg(res.msg);
                setTimeout(function (){
                    layer.closeAll();
                },1000);
                $("#upload_form").attr("disabled", false);
                $("#upload_form").attr("class", "layui-btn");
                table.reload('deviceTable');
            },
        });
        return false;
    });

    $("#cancel_form").on('click',function (){
        layer.closeAll();
        return false;
    });
    $("#syncDevice").on('click', function (){
        layer.confirm('同步数据，是否继续？', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            var index = layer.load(2, {
                shade: [0.4, '#000'],
                content: '同步中...',
                success: function (layero) {
                    layero.find('.layui-layer-content').css({
                        'padding-top': '40px',
                        'width': '200px'
                    });
                }
            });
            $.post('/qzsqDevice/syncData',{},function (res) {
                if(res.status === 200){
                    layer.msg(res.msg,{
                        time:1000,
                        end:function () {
                            reload();
                        }
                    });
                }else{
                    layer.msg(res.msg);
                }
                layer.close(index);
            });
        });
    });

});

function parseSbly(type) {
    if(typeof status == "undefined" || status == null){
        return "未知";
    }
    switch (Number(type)) {
        case 1: return '人脸抓拍';
        case 2: return '视频监控';
        case 3: return '一键报警柱';
        case 4: return '智能门禁';
        case 5: return '用电监测';
        case 6: return '用水监测';
        case 7: return '高空监控';
        case 8: return '电动车过车设备';
        case 9: return '密度摄像机';
        case 10: return '访客设备';
        case 11: return '车辆道闸';
        case 12: return '电子围栏';
        case 13: return 'WIFI探针';
        case 14: return '其它';
        default: return "未知";
    }
}

function reload(){
    location.reload();
}
function hasDictKey(key) {
    for(var i in dictKeyArray){
        if(dictKeyArray[i].key === key){
            return true;
        }
    }
    return false;
}

function changeUnit(e) {
    var name = $("#searcheKey").val();
    currComunityId = layui.$(e).attr('id');
    layui.$('.floor-item').css('background-color', 'transparent')
    layui.$(e).css('background-color', '#f1f1f1')
    layui.table.reload('deviceTable', {
        page: {
            curr: 1 //重新从第 1 页开始
        },
        where: {'communityId': currComunityId,'name':name}
    });
    loadBuildingList(currComunityId,'blockId','unitId');
}
function loadBuildingList(val,blockId,unitId,selectedBlock,selectedUnit){
    $.get('/qzsqDevice/loadBuildingList', {communityId:val}, function (result) {
        $("#"+blockId).empty();
        $("#"+unitId).empty();
        if(result != null){
            if(result.data != null){
                var $opt_html = "<option value=''>请选择</option>";
                $.each(result.data, function (index, item) {
                    $opt_html += "<option value='" + item.lyxxId + "'>" + item.lyxxName + "</option>";
                    if(!hasDictKey(item.lyxxId)){
                        var obj = {"key":item.lyxxId, "data":item.data};
                        dictKeyArray.push(obj);
                    }
                });
                $("#"+blockId).empty().append($opt_html);
                if(selectedBlock){
                    $("#"+blockId).val(selectedBlock);
                }
                layui.form.render('select');
                loadUnitList($("#"+blockId).val(),unitId,selectedUnit);
            }
        }

    });
}

function loadUnitList(val,unitId,selectedUnit){
    for(var i in dictKeyArray){
        if(dictKeyArray[i].key === val){
            var units = dictKeyArray[i].data;
            var $opt_html = "<option value=''>请选择</option>";
            $.each(units, function (index, item) {
                $opt_html += "<option value='" + item.id + "'>" + item.unitName + "</option>";
            });
            $("#"+unitId).empty().append($opt_html);
            if(selectedUnit){
                $("#"+unitId).val(selectedUnit);
            }
            layui.form.render('select');
            break;
        }
    }
}